package com.yz.crm.weixin.util;


import com.yz.common.property.PropertyReader;
import com.yz.common.util.HttpClientUtil;
import com.yz.common.util.JDKStackTrace;
import com.yz.common.util.JsonUtils;
import com.yz.crm.weixin.model.general.WechatJsSDKConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by DOVE on 2015/8/29.
 */
public class WechatUtils {
    private static Logger logger = Logger.getLogger(WechatUtils.class);

    public static String getAuthRedirectUrl(String authUrl, String visitorRedirectService) {
        String willOpenUrl =  PropertyUtils.getValue("wechat.redirect.url", "",
                new String[]{
                        PropertyUtils.getValue("wechat.visitor.appid", ""),
                        visitorRedirectService,
                        authUrl
                });
        return willOpenUrl;
    }

    public static WechatJsSDKConfig getJsSDKConfig(String url) {
        WechatJsSDKConfig wechatJsSDKConfig = null;

        Map param = new HashMap();
        param.put("url", url);
        String jsconfigUrl = PropertyUtils.getValue("weixin.gzh.jsconfig", "");
        String jsConfigStr = HttpClientUtil.post(jsconfigUrl, param, null);

        if (StringUtils.isNotEmpty(jsConfigStr)) {
            try {
                JSONObject ValidResult = JSONObject.fromObject(jsConfigStr);
                wechatJsSDKConfig = JsonUtils.toObject(ValidResult.getString("data"), WechatJsSDKConfig.class);
            } catch (Exception e) {
                logger.info("url:" + url + ",jsConfigStr:" + jsConfigStr + JDKStackTrace.getJDKStrack(e));
                wechatJsSDKConfig = new WechatJsSDKConfig();
            }
        }
        return wechatJsSDKConfig == null ? new WechatJsSDKConfig() : wechatJsSDKConfig;
    }
}
